#pragma once
#include <stdarg.h>
#include <string>
#include <cstdio>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>

#define LOG_NORMAL "log.txt"
#define LOG_ERROR "err.txt"
enum level
{
    DEBUG = 0,
    NORMAL,
    WARNING,
    ERROR,
    FAULT,
};

std::string lvtostring(enum level &lv)
{
    switch (lv)
    {
    case DEBUG:
        return "DEBUG";
    case NORMAL:
        return "NORMAL";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FAULT:
        return "FAULT";
    default:
        break;
    }
    return nullptr;
}

bool timetodata(time_t stamp, char* data)
{
    struct tm* p;
    p = gmtime(&stamp);
    int ret = strftime(data, 64, "%Y-%m-%d %H:%M:%S", p);
    if(ret == 0)
    {
        std::cout << "缓冲区空间不足" << std::endl;
        return false;
    }
    data[ret] = '\0';
    return true;
}


int log_message(enum level lv, const char *format, ...)
{
    chdir("./Log");
    std::string lv_string = lvtostring(lv);
    //时间戳转换成日期格式
    char data[64];
    timetodata(time(nullptr), data);
    char logprefix[1024];
    snprintf(logprefix, 1024, "[%s][%s][pid:%d]:", lv_string.c_str(), data, getpid());
    char logmessage[1024];
    // 获取参数列表
    va_list arg;
    va_start(arg, format);
    vsnprintf(logmessage, 1024, format, arg);
    // 清除申请的可变参数空间
    va_end(arg);
    std::ofstream log(LOG_NORMAL, std::ios::app);
    std::ofstream log_err(LOG_ERROR, std::ios::app);
    if (log.good() && log_err.good())
    {
        switch (lv)
        {
        case DEBUG:
        case NORMAL:
        case WARNING:
            log << logprefix << logmessage << std::endl;
            break;
        case ERROR:
        case FAULT:
            log_err << logprefix << logmessage << std::endl;
            break;
        default:
            break;
        }
    }
    else
        return -1;
    log.close();
    log_err.close();
    
    return 0;
}
